//
//  WBPictureSelectorController.swift
//  SinaWeibo
//
//  Created by 风不会停息 on 2016/11/23.
//  Copyright © 2016年 风不会停息. All rights reserved.
//

import UIKit
import SVProgressHUD

let colCount: CGFloat = 3
let selectorMargin: CGFloat = 4
let selectorCellWidth = (ScreenWidth - (colCount + 1) * selectorMargin) / colCount

private let reuseIdentifier = "Cell"
private let maxCount = 3

class WBPictureSelectorController: UICollectionViewController {

    
    
    lazy var selectedImage:[UIImage] = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.view.isHidden = selectedImage.count == 0
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        let delta = self.selectedImage.count == maxCount ? 0 : 1
        return self.selectedImage.count + delta
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PictureSelectorCell
    
        cell.backgroundColor = randomColor()
        cell.delegate = self
        
        if indexPath.item == self.selectedImage.count {
            //给最后一个cell的数据赋值
            cell.image = nil
        } else {
            cell.image = self.selectedImage[indexPath.item]
        }
        return cell
    }

    

}


extension WBPictureSelectorController:PictureSelectorDelegate{
    
    
    func userWillChoose(cell:PictureSelectorCell?) {
        

        let imagePickVC = UIImagePickerController()
        
        imagePickVC.delegate = self
        
        self.present(imagePickVC, animated: true, completion: nil)
    }
    
    func userWillRemovew(cell:PictureSelectorCell) {

        guard let indexpath = collectionView?.indexPath(for: cell) else {
            return
        }
        self.selectedImage.remove(at: indexpath.item)
        //2.刷新数据
        self.collectionView?.reloadData()
        self.view.isHidden = self.selectedImage.count == 0
        
    }
    
    
}
//遵守选择器的代理协议，必须要同时遵守uinavDelegate
//代理方法是为了把选中的图片保存到数组中，使用该代理方法需要手动dismiss
extension WBPictureSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        //新浪微博的接口对上传图片的大小有限制，所以要进行缩放处理
        self.selectedImage.append(image.scaleImage(width: ScreenWidth))
        
        dismiss(animated: true) {
            self.collectionView?.reloadData()
        }
        self.collectionView?.reloadData()
    }
    
    
}

@objc protocol PictureSelectorDelegate: NSObjectProtocol{
    
    //可选类型的协议方法
    @objc optional func userWillChoose(cell:PictureSelectorCell)
    
    @objc optional func userWillRemovew(cell:PictureSelectorCell)
    
}

class PictureSelectorCell:UICollectionViewCell{
    
    // 用weak修饰代理不会出现循环引用的问题，var可以不在初始化中赋值
    weak var delegate : PictureSelectorDelegate?
    
    
    var image: UIImage? {
        didSet {
            //设置添加按钮的image
            addBtn.setImage(image, for: .normal)
//            self.isHidden = image == nil
            removeBtn.isHidden = image == nil
        }
    }
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    lazy var addBtn:UIButton = {
        
        let btn = UIButton()
        
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        return btn
    }()
    lazy var removeBtn:UIButton = {
        
        let btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        return btn
    }()
    
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUI(){
        
        self.contentView.addSubview(addBtn)
        self.contentView.addSubview(removeBtn)
        
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        removeBtn.snp.makeConstraints { (make) in
            make.top.right.equalTo(self)
            
        }
        
        addBtn.addTarget(self, action: #selector(add), for: .touchUpInside)
        removeBtn.addTarget(self, action: #selector(remove), for: .touchUpInside)
        
        
    }
    @objc private func add(){
        
        
        if image != nil {
//            print("人家已经有啦")
            SVProgressHUD.showError(withStatus: "已经有图片了哦")
            return
        }
        
        self.delegate?.userWillChoose?(cell: self)
        
    }
    @objc private func remove(){
        
        
        self.delegate?.userWillRemovew?(cell: self)
        
    }
    
    
}
